<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/13
 * Time: 13:38
 */
namespace App\DownloadMusic;
use Service\DownloadMusic\IndexService;
use cli\Notify;

class IndexController
{
	public $IndexService;
	public $menu = [
		'input'=>'搜索音乐',
		'choose'=>'浏览目录',
		'update'=>'更新数据',
	];
	public $headers = array('id','歌名');
	public $browseFile = [
		'next'=>'下一页',
		'last'=>'上一页',
		'back'=>'返回',
	];

	public $inputMenu = [
		'down'=>'下载',
		'back'=>'返回',
	];
	public $notify;
	public $type = true;
	public function __construct()
	{
		$this->IndexService =  new  IndexService();
		
		while ($this->type) {
			$choice = \cli\menu($this->menu, null, '请选择');
			\cli\line();
			if($choice=='input'){
				$this->name($this->input());
				break;
			}
			if ($choice == 'choose') {
				$this->browseFile();
				break;
			}
			if($choice=='update'){
				$this->update();
				break;
			}
		}
	}
	
	public function name($name=''){
		$data = $this->IndexService->getMusicFile();
		$search = [];
		foreach ($data as $key =>$value){
			if(strpos($value['article_title'],$name) !== false){
				$search[] = $value;
			}
		}
		$this->setTable($search);
		while ($this->type) {
			$choice = \cli\menu($this->inputMenu, null, '请选择');
			\cli\line();
			if($choice=='down'){
				fwrite( STDOUT, sprintf( '%s: ', '请输入id' ) );
				$id= \cli\input();
				$this->IndexService->DownMusicFile($id);
				break;
			}
			if($choice=='back'){
				self::__construct();
				break;
			}
		}
	}
	
	
	public function input(){
		fwrite( STDOUT, sprintf( '%s: ', '请输入歌名' ) );
		$name = \cli\input();
		if($name==''){
			self::input();
		}
		return $name;
	}
	
	public function update(){
		$data = $this->IndexService->updateMusicFile();
		\cli\line();
		fwrite( STDOUT, sprintf( '已更新歌曲%s首 ', $data ) );
	}

	public function browseFile($page = 1 ,$size = 20){
	
		$data = $this->IndexService->getMusicFile();
		$data = array_slice($data,($page-1)*$size,$size);
	
		$this->setTable($data);

		while ($this->type) {
			$choice = \cli\menu($this->browseFile, null, '请选择');
			\cli\line();
			if($choice=='next'){
				self::browseFile($page+1,$size);
				break;
			}
			if ($choice == 'last') {
				if($page<=1)$page = 2;
				self::browseFile($page-1,$size);
				break;
			}
			if($choice=='back'){
				self::__construct();
				break;
			}
		}
	}
	
	public function setTable($data){
		$table = new \cli\Table();
		$table->setHeaders($this->headers);
		$table->setRows($data);
		$table->setRenderer(new \cli\table\Ascii([20,100]));
		$table->display();
	}
}